import { storageLocal } from "/@/utils/storage";
/**
将以下格式
{
  '0': 'name1',
  '1': 'name2'
}
转化为select option常用格式
  [
    { value: "1", label: "启用" },
    { value: "0", label: "禁用" }
  ]
 */
export function formatOption(obj, key = "value", lable = "label") {
  if (!(Object.prototype.toString.call(obj) === "[object Object]")) {
    return obj;
  }
  const keys = Object.keys(obj);
  const arr = [];
  keys.forEach(item => {
    arr.push({
      [key]: item,
      [lable]: obj[item]
    });
  });

  return arr;
}

// //根据id 找树结构数据中的某一个节点
export function findPathbyId(arr, path) {
  let target = null;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].menuPath === path) {
      target = arr[i];
      break;
    } else {
      if (arr[i].children) {
        target = findPathbyId(arr[i].children, path);
        if (target) {
          break;
        }
      }
    }
  }
  return target;
}

//友盟埋点自定义点击事件
export const clickEvent = (category = "", action = "", label = "") => {
  const objLabel = {};
  if (label) {
    objLabel.description = label;
  }
  const userInfo = storageLocal.getItem("info");
  if (userInfo && userInfo.username) {
    objLabel.loginname = userInfo.username;
  }
  try {
    window._czc &&
      window._czc.push([
        "_trackEvent",
        category,
        `[${action}]`,
        JSON.stringify(objLabel)
      ]);
  } catch (err) {
    console.log(err);
  }
};

//四舍五入保留n位小数
export const roundToDecimal = (num,n) => {
  if (!num) {
  	return 0
  }else{
    const square = Math.pow(10, n || 2);
    return Math.round(num * square) / square;
  }
}

// fixNum:保留的小数位数
//小数转为百分比，并四舍五入保留几位小数
export const toFixPercent = (num = 0,fixNum = 2) =>{
  if (!num) {
  	return 0
  }else{
    let num1 = Number(num)*100 || 0;
    let fixNum1 = Math.pow(10,Number(fixNum));
    return Math.round(num1*fixNum1)/fixNum1;
  }
}

//金额转为以万为单位
export const toWanUnit = (num = 0,fixNum = 2) =>{
  if (!num) {
  	return 0
  }else{
    let num1 = Number(num)/10000 || 0;
    let fixNum1 = Math.pow(10,Number(fixNum));
    return Math.round(num1*fixNum1)/fixNum1;
  }
}
